﻿/**
//  frmAdmin.cs
//  Marquee Moment
//  Copyright 2011 Systematix Technocrates. All rights reserved.
**/
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using MarqueeMoment.Entities;
using NLog;
using System.Text.RegularExpressions;
using System.Drawing;

namespace MarqueeMoment.Forms
{
    public partial class frmAdmin : Form
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        #region for Variable Declaration
        Int32 selectedAdmin = 1;

        #region DataTable Variable
        DataTable _dtUser;
        DataTable _dtCustomer;
        DataTable _dtMessage;
        DataTable _dtArchive;
        #endregion DataTable Variable
        
        #region Flag Variable
        bool _loadCustomerFlag = false;
        bool _loadMessageFlag = false;
        bool _loadArchiveFlag = false;
        bool _loadUserFlag = false;
        bool _addModeMessageFlag = false;
        bool _addModeUserFlag = false;
        bool _addModeCustomerFlag = false;
        bool _editModeMessageFlag = false;
        bool _editModeUserFlag = false;
        bool _editModeCustomerFlag = false;
        #endregion Flag Variable

        #region Pagination Variable
        private int _mintMessageTotalRecords = 0;
        private int _mintMessagePageSize = 0;
        private int _mintMessagePageCount = 0;
        private int _mintMessagecurrentPage = 1;
        private const int _pageCountMessage = 10;

        private int _mintUserTotalRecords = 0;
        private int _mintUserPageSize = 0;
        private int _mintUserPageCount = 0;
        private int _mintUsercurrentPage = 1;
        private const int _pageCountUser = 10;

        private int _mintCustomerTotalRecords = 0;
        private int _mintCustomerPageSize = 0;
        private int _mintCustomerPageCount = 0;
        private int _mintCustomercurrentPage = 1;
        private const int _pageCountCustomer = 10;

        private int _mintArchiveTotalRecords = 0;
        private int _mintArchivePageSize = 0;
        private int _mintArchivePageCount = 0;
        private int _mintArchivecurrentPage = 1;
        private const int _pageCountArchive = 4;

        #endregion Pagination Variable

        #endregion for variable Declaration

        #region Constructor

        public frmAdmin()
        {
            logger.Info("On frmAdmin()");
            InitializeComponent();
            InitializeValues();
        }

        #endregion Constructor

        #region FormLoad

        private void InitializeValues()
        {
            logger.Info("On InitializeValues()");
            ShowTime();
            RefreshGridUser(0);
            loadCustomerNameCombo();
        }

        #endregion FormLoad

        #region User defined Methods

        #region for Users

        /// <summary>
        /// Set Default value for User Grid
        /// </summary>
        private void SetDefaultGridUser()
        {
            logger.Info("On SetDefaultGridUser()");
            _addModeUserFlag = false;
            _editModeUserFlag = false;
            RefreshGridUser(this._mintUsercurrentPage);
        }
        
        /// <summary>
        /// It is used for refreshing user grid after the operation Insertion, Deletion and updation of the record. 
        /// </summary>
        /// <param name="currentPageUser">currentPageUser contains the Index of Currentpage</param>
        /// 
        private void RefreshGridUser(Int32 currentPageUser)
        {
            logger.Info("On RefreshGridUser(Int32 currentPageUser) ,currentPageUser:" + currentPageUser.ToString());
            try
            {
                dgUsers.DataSource = null;
                dgUsers.Columns.Clear();
                dgUsers.AllowUserToResizeColumns = false;
                dgUsers.AllowUserToResizeRows = false;

                DataGridViewCheckBoxColumn chkSelectUser = new DataGridViewCheckBoxColumn();
                chkSelectUser.Name = "chkSelectUser";
                chkSelectUser.HeaderText = string.Empty;
                chkSelectUser.DisplayIndex = 0;
                chkSelectUser.Width = 40;

                DataGridViewTextBoxColumn UserId = new DataGridViewTextBoxColumn();
                UserId.DataPropertyName = "UserId";
                UserId.Name = "UserId";
                UserId.HeaderText = "UserId";
                UserId.Width = 100;
                UserId.Visible = false;

                DataGridViewTextBoxColumn UserName = new DataGridViewTextBoxColumn();
                UserName.DataPropertyName = "UserName";
                UserName.Name = "UserName";
                UserName.HeaderText = "Username";
                UserName.Width = 152;

                DataGridViewTextBoxColumn Password = new DataGridViewTextBoxColumn();
                Password.DataPropertyName = "Password";
                Password.Name = "Password";
                Password.HeaderText = "Password";
                Password.Width = 152;

                DataGridViewCheckBoxColumn chkUserType = new DataGridViewCheckBoxColumn();
                chkUserType.DataPropertyName = "UserType";
                chkUserType.Name = "chkUserType";
                chkUserType.HeaderText = "Admin Access";
                chkUserType.Width = 100;

                DataGridViewButtonColumn btnUserHeader1 = new DataGridViewButtonColumn();
                btnUserHeader1.Name = "btnUserHeader1";
                btnUserHeader1.HeaderText = string.Empty;
                btnUserHeader1.Width = 58;

                DataGridViewButtonColumn btnUserHeader2 = new DataGridViewButtonColumn();
                btnUserHeader2.Name = "btnUserHeader2";
                btnUserHeader2.HeaderText = string.Empty;
                btnUserHeader2.Width = 58;

                dgUsers.Columns.Add(chkSelectUser);
                dgUsers.Columns.Add(UserId);
                dgUsers.Columns.Add(UserName);
                dgUsers.Columns.Add(Password);
                dgUsers.Columns.Add(chkUserType);
                dgUsers.Columns.Add(btnUserHeader1);
                dgUsers.Columns.Add(btnUserHeader2);

                loadUserPage(currentPageUser);
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                dgUsers.EndEdit();
            }
        }

        /// <summary>
        /// For cancelling the edit mode of the grid 
        /// </summary>
        private void cancelEditModeUser()
        {
            logger.Info("On cancelEditModeUser()");
            foreach (DataGridViewRow row in dgUsers.Rows)
            {
                row.Cells["btnUserHeader1"].Value = "Edit";
                row.Cells["btnUserHeader2"].Value = "Delete";

                readOnlyTrueColumnsUser(row.Index);

                dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value = false;
            }
        }

        /// <summary>
        ///Only at the editing time of the row readonly will set to false
        /// </summary>
        /// <param name="rowIndex">Contains paticular row index </param>
        private void readOnlyTrueColumnsUser(int rowIndex)
        {
            logger.Info("On readOnlyTrueColumnsUser(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgUsers.Rows[rowIndex].Cells["UserName"].ReadOnly = true;
            dgUsers.Rows[rowIndex].Cells["Password"].ReadOnly = true;
            dgUsers.Rows[rowIndex].Cells["chkUserType"].ReadOnly = true;
        }

        /// <summary>
        /// To set focus on UserName column of grid
        /// </summary>
        /// <param name="rowIndex">Grid Row Index on which focus will set</param>
        private void focusUserName(int rowIndex)
        {
            logger.Info("On focusUserName(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgUsers.Focus();
            dgUsers.CurrentCell = dgUsers.Rows[rowIndex].Cells["Password"];
            dgUsers.CurrentCell.Style.BackColor = Color.LightGray;
            dgUsers.CurrentCell = dgUsers.Rows[rowIndex].Cells["UserName"];
            dgUsers.CurrentCell.Style.BackColor = Color.LightGray;   
            dgUsers.BeginEdit(true);
        }

        /// <summary>
        ///Only at the editing time of the row readonly will set to false
        /// </summary>
        /// <param name="rowIndex">Contains paticular row index </param>
        private void readOnlyFalseColumnsUsers(int rowIndex)
        {
            logger.Info("On readOnlyFalseColumnsUsers(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgUsers.Rows[rowIndex].Cells["UserName"].ReadOnly = false;
            dgUsers.Rows[rowIndex].Cells["Password"].ReadOnly = false;
            dgUsers.Rows[rowIndex].Cells["chkUserType"].ReadOnly = false;
        }

        private void dgUsers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            logger.Info("On dgUsers_CellClick(object sender, DataGridViewCellEventArgs e)");
            if (e.RowIndex >= 0)
            {
                logger.Info("On dgUsers_CellClick(), e.ColumnIndex:" + e.ColumnIndex.ToString());
                if (e.ColumnIndex == dgUsers.Columns["btnUserHeader1"].Index)
                {
                    if (dgUsers.Rows[e.RowIndex].Cells["btnUserHeader1"].Value.ToString() == "Edit" && _addModeUserFlag == false && _editModeUserFlag == false)
                    {
                        logger.Info("On dgUsers_CellClick(), Edit Clicked");
                        readOnlyFalseColumnsUsers(e.RowIndex);
                        
                        dgUsers.Rows[e.RowIndex].Cells["btnUserHeader1"].Value = "Save";
                        dgUsers.Rows[e.RowIndex].Cells["btnUserHeader2"].Value = "Cancel";                 
                        _editModeUserFlag = true;
                        focusUserName(e.RowIndex);
                    }
                    else if (dgUsers.Rows[e.RowIndex].Cells["btnUserHeader1"].Value.ToString() == "Save")//Save
                    {
                        logger.Info("On dgUsers_CellClick(), Save Clicked with UserName:" + dgUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString().Trim() + ",Password:" + dgUsers.Rows[e.RowIndex].Cells["Password"].Value.ToString().Trim());
                        UserEntity user = new UserEntity();
                        user.UserId = Convert.ToInt32(dgUsers.Rows[e.RowIndex].Cells["UserId"].Value);
                        user.UserName = dgUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString().Trim();
                        user.Password = PasswordEncodeDecode.Base64Encode(dgUsers.Rows[e.RowIndex].Cells["Password"].Value.ToString().Trim());
                        if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password))
                        {
                            Dialogs.EmptyField();
                            return;
                        }
                        user.UserType = Convert.ToBoolean(dgUsers.Rows[e.RowIndex].Cells["chkUserType"].Value);
                        Boolean existUserFlag = false;
                        existUserFlag = UserEntity.IsExistUser(user);
                        if (existUserFlag == false)
                        {
                            UserEntity.Update(user);
                            cancelEditModeUser();
                            dgUsers.Rows[e.RowIndex].Cells["Password"].Style.BackColor = Color.White;
                            dgUsers.Rows[e.RowIndex].Cells["UserName"].Style.BackColor = Color.White;
                            _editModeUserFlag = false;
                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            focusUserName(e.RowIndex);
                        }
                    }

                    else if (dgUsers.Rows[e.RowIndex].Cells["btnUserHeader1"].Value.ToString() == "Add")//Add
                    {
                        logger.Info("On dgUsers_CellClick(), Add Clicked with UserName:" + dgUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString().Trim() + ",Password:" + dgUsers.Rows[e.RowIndex].Cells["Password"].Value.ToString().Trim());
                        UserEntity user = new UserEntity();
                        user.UserName = dgUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString().Trim();
                        user.Password = PasswordEncodeDecode.Base64Encode(dgUsers.Rows[e.RowIndex].Cells["Password"].Value.ToString().Trim());
                        if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password))
                        {
                            Dialogs.EmptyField();
                            return;
                        }
                        user.UserType = Convert.ToBoolean(dgUsers.Rows[e.RowIndex].Cells["chkUserType"].Value);

                        Boolean existUserFlag = false;
                        existUserFlag = UserEntity.IsExistUser(user);
                        if (existUserFlag == false)
                        {
                            UserEntity.Insert(user);
                            RefreshGridUser(this._mintUsercurrentPage);
                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            focusUserName(e.RowIndex);
                        }

                    }
                }
                else if (e.ColumnIndex == dgUsers.Columns["btnUserHeader2"].Index)
                {
                    logger.Info("On dgUsers_CellClick(), Delete Clicked with UserId:" + dgUsers.Rows[e.RowIndex].Cells["UserId"].Value.ToString());
                    if (dgUsers.Rows[e.RowIndex].Cells["btnUserHeader2"].Value.ToString() == "Delete")
                    {
                        Int32 userId = Convert.ToInt32(dgUsers.Rows[e.RowIndex].Cells["UserId"].Value);
                        frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
                        customBox.ShowDialog();

                        if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            logger.Info("On dgUsers_CellClick(), User deleting...");
                            if (frmMainMenu.user != null && frmMainMenu.user.UserId > 0 && frmMainMenu.user.UserId == userId)
                            {
                                logger.Info("On dgUsers_CellClick(),You cannot delete the current logged in user");
                                Dialogs.Information("You cannot delete the current logged in user");
                            }
                            else
                            {
                                UserEntity.Delete(userId);
                                logger.Info("On dgUsers_CellClick(), Deleted User: UserName: " + dgUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString() + " with UserId: " + userId.ToString());

                                //Maintan last page on delete
                                Int32 currentPage = this._mintUsercurrentPage;
                                if (dgUsers.RowCount > 1)
                                    currentPage = this._mintUsercurrentPage;
                                else if (currentPage > 0)
                                    currentPage--;
                                else
                                    currentPage = 0;
                                RefreshGridUser(currentPage);
                            }                             
                        }


                    }
                    else if (dgUsers.Rows[e.RowIndex].Cells["btnUserHeader2"].Value.ToString() == "Cancel") //Cancel
                    {
                        logger.Info("On dgUsers_CellClick(), Cancel Clicked");
                        dgUsers.Rows[e.RowIndex].Cells["Password"].Style.BackColor = Color.White;
                        dgUsers.Rows[e.RowIndex].Cells["UserName"].Style.BackColor = Color.White;
                        _addModeUserFlag = false;
                        _editModeUserFlag = false;
                        RefreshGridUser(this._mintUsercurrentPage);
                    }
                }

            }


        }

        private void lnkUsersSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkUsersSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            Boolean allChecked = true;

            foreach (DataGridViewRow row in dgUsers.Rows)
            {
                if (!(dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value.Equals(true)))
                {
                    allChecked = false;
                    dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value = true;
                }
            }

            if (allChecked)
                foreach (DataGridViewRow row in dgUsers.Rows)
                    dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value = false;
        }

        //private void lnkUsersSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    logger.Info("On lnkUsersSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
        //    foreach (DataGridViewRow row in dgUsers.Rows)
        //    {
        //        dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value = true;
        //    }
        //}

        private void lnkUsersDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkUsersDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (dgUsers == null || dgUsers.RowCount == 0)
                return;

            if (_addModeUserFlag)
            {
                logger.Info("lnkUsersDelete_LinkClicked(),_addModeUserFlag:True, delete action cancelled");
                Dialogs.Exclamation("There are unsaved changes on the tab.\nPlease either save the row or cancel it from Cancel button");
                return;
            }

           bool selectedRowCount = false;
            foreach (DataGridViewRow row in dgUsers.Rows)
                if (dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value != null && (bool)dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value)
                {
                    selectedRowCount = true;
                    break;
                }

            if (!selectedRowCount)
            {
                Dialogs.Exclamation("No record selected");
                return;
            }

            frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
            customBox.ShowDialog();
            if (customBox.DialogResult == System.Windows.Forms.DialogResult.No)
                return;

            Int32 selectedCount = 0;
            foreach (DataGridViewRow row in dgUsers.Rows)
            {
                if (dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value != null && (bool)dgUsers.Rows[row.Index].Cells["chkSelectUser"].Value)
                {
                    if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        Int32 userId = Convert.ToInt32(dgUsers.Rows[row.Index].Cells["UserId"].Value);
                        if (frmMainMenu.user != null && frmMainMenu.user.UserId > 0 && frmMainMenu.user.UserId == userId)
                        {
                            logger.Info("lnkUsersDelete_LinkClicked(), cannot delete the current logged in user, UserId:" + userId.ToString());
                            Dialogs.Information("You cannot delete the current logged in user");
                        }
                        else
                        {
                            UserEntity.Delete(userId);
                            logger.Info("Deleted User: UserName: " + dgUsers.Rows[row.Index].Cells["UserName"].Value.ToString() + " with UserId: " + userId.ToString());
                            selectedCount++;
                        }
                    }
                }
            }

            //Maintan last page on delete
            Int32 currentPage = this._mintUsercurrentPage;
            if (dgUsers.RowCount > selectedCount)
                currentPage = this._mintUsercurrentPage;
            else if (currentPage > 0)
                currentPage--;
            else
                currentPage = 0;
            RefreshGridUser(currentPage);
        }

        private void lnkUsersAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkUsersAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (_addModeUserFlag)
            {
                logger.Info("On lnkUsersAdd_LinkClicked(), _addModeUserFlag:True , Action cancelled"); 
                Dialogs.Exclamation("You already have one unsaved row on your tab.\nPlease either save or cancel it before adding another row.");
                return;
            }
            _addModeUserFlag = true;
            DataRow dr = _dtUser.NewRow();
            dr[0] = 0;
            dr[1] = string.Empty;
            dr[2] = string.Empty;
            dr[3] = false;
            _dtUser.Rows.Add(dr);
            _dtUser.AcceptChanges();

            foreach (DataGridViewRow row in dgUsers.Rows)
                if (row.Index == dgUsers.RowCount - 1)
                {
                    readOnlyFalseColumnsUsers(row.Index);
                    dgUsers.Rows[dgUsers.RowCount - 1].Cells["btnUserHeader1"].Value = "Add";
                    dgUsers.Rows[dgUsers.RowCount - 1].Cells["btnUserHeader2"].Value = "Cancel";

                    focusUserName(row.Index);
                }
                else
                {
                    readOnlyTrueColumnsUser(row.Index);
                    row.Cells["btnUserHeader1"].Value = "Edit";
                    row.Cells["btnUserHeader2"].Value = "Delete";
                }
        }

        private void dgUsers_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            logger.Info("On dgUsers_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)");
            if (String.IsNullOrEmpty(e.FormattedValue.ToString())) //run some custom validation on the value in that cell
            {
                dgUsers.Rows[e.RowIndex].ErrorText = "User Name must not be empty";                
            }
            else
                dgUsers.Rows[e.RowIndex].ErrorText = String.Empty;
        }

        #region Pagination In User

        /// <summary>
        /// To get total no of user count
        /// </summary>
        /// <returns>count</returns>
        private int getUserCount()
        {
            logger.Info("On ");
            int intCount = 0;
            intCount = UserEntity.SelectRowCountUser();
            return intCount;
        }

        /// <summary>
        /// To go first page
        /// </summary>
        private void goUserFirst()
        {
            logger.Info("On goUserFirst()");
            this._mintUsercurrentPage = 0;

            loadUserPage(this._mintUsercurrentPage);
        }

        /// <summary>
        /// To go Prev. Page
        /// </summary>
        private void goUserPrevious()
        {
            logger.Info("On goUserPrevious()");
            if (this._mintUsercurrentPage == this._mintUserPageCount)
                this._mintUsercurrentPage = this._mintUserPageCount - 1;

            this._mintUsercurrentPage--;

            if (this._mintUsercurrentPage < 1)
                this._mintUsercurrentPage = 0;

            loadUserPage(this._mintUsercurrentPage);
        }

        /// <summary>
        /// To go next page
        /// </summary>
        private void goUserNext()
        {
            logger.Info("On goUserNext()");
            this._mintUsercurrentPage++;

            if (this._mintUsercurrentPage > (this._mintUserPageCount - 1))
                this._mintUsercurrentPage = this._mintUserPageCount - 1;

            loadUserPage(this._mintUsercurrentPage);
        }

        /// <summary>
        /// To go last page
        /// </summary>
        private void goUserLast()
        {
            logger.Info("On goUserLast()");
            this._mintUsercurrentPage = this._mintUserPageCount - 1;

            loadUserPage(this._mintUsercurrentPage);
        }

        /// <summary>
        /// For Page view.Adjust page count if the last page contains partial page.
        /// </summary>
        /// <param name="currentPageMessage">It is the current page Index</param>
        private void InitializePagingUser(Int32 currentPageUser)
        {
            logger.Info("On InitializePagingUser(Int32 currentPageUser), currentPageUser:" + currentPageUser.ToString());
            this._mintUserPageSize = _pageCountUser;
            this._mintUserTotalRecords = getUserCount();
            this._mintUserPageCount = this._mintUserTotalRecords / this._mintUserPageSize;

            if (this._mintUserTotalRecords % this._mintUserPageSize > 0)
                this._mintUserPageCount++;

            this._mintUsercurrentPage = currentPageUser;

        }

        /// <summary>
        /// For loading the selected page in pagination
        /// </summary>
        private void loadUserPage(Int32 currentPageUser)
        {
            logger.Info("On loadUserPage(Int32 currentPageUser), currentPageUser:" + currentPageUser.ToString());
            logger.Info("On loadUserPage() ,check bgWorker.IsBusy:" + bgWorker.IsBusy.ToString());
            if (bgWorker.IsBusy != true)
            {
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork_loadUserPage);
                bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_loadUserPage);
                bgWorker.RunWorkerAsync(currentPageUser);

            }
        }

        private void btnUserFirst_Click(object sender, EventArgs e)
        {
            logger.Info("On btnUserFirst_Click(object sender, EventArgs e)");
            this.goUserFirst();
        }

        private void btnUserPrevious_Click(object sender, EventArgs e)
        {
            logger.Info("On btnUserPrevious_Click(object sender, EventArgs e)");
            this.goUserPrevious();
        }

        private void btnUserNext_Click(object sender, EventArgs e)
        {
            logger.Info("On btnUserNext_Click(object sender, EventArgs e)");
            this.goUserNext();
        }

        private void btnUserLast_Click(object sender, EventArgs e)
        {
            logger.Info("On btnUserLast_Click(object sender, EventArgs e)");
            this.goUserLast();
        }


        #endregion In User

        #region BackgroundWorker User

        //private void bgWorker_DoWork_RefreshGridUser(object sender, DoWorkEventArgs e)
        //{
        //    Int32 currentPageUser = 0;
        //    Object objCurrentPageUser = e.Argument as Object;
        //    if (objCurrentPageUser != null)
        //        currentPageUser = (Int32)objCurrentPageUser;

        //    InitializePagingUser(currentPageUser);
        //}

        //private void bgWorker_Completed_RefreshGridUser(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    dgUsers.DataSource = null;
        //    dgUsers.Columns.Clear();

        //    DataGridViewCheckBoxColumn chkSelectUser = new DataGridViewCheckBoxColumn();
        //    chkSelectUser.Name = "chkSelectUser";
        //    chkSelectUser.HeaderText = string.Empty;
        //    chkSelectUser.DisplayIndex = 0;
        //    chkSelectUser.Width = 40;

        //    DataGridViewTextBoxColumn UserId = new DataGridViewTextBoxColumn();
        //    UserId.DataPropertyName = "UserId";
        //    UserId.Name = "UserId";
        //    UserId.HeaderText = "UserId";
        //    UserId.Width = 100;
        //    UserId.Visible = false;

        //    DataGridViewTextBoxColumn UserName = new DataGridViewTextBoxColumn();
        //    UserName.DataPropertyName = "UserName";
        //    UserName.Name = "UserName";
        //    UserName.HeaderText = "User Name";
        //    UserName.Width = 100;

        //    DataGridViewTextBoxColumn Password = new DataGridViewTextBoxColumn();
        //    Password.DataPropertyName = "Password";
        //    Password.Name = "Password";
        //    Password.HeaderText = "Password";
        //    Password.Width = 100;

        //    DataGridViewCheckBoxColumn chkUserType = new DataGridViewCheckBoxColumn();
        //    chkUserType.DataPropertyName = "UserType";
        //    chkUserType.Name = "chkUserType";
        //    chkUserType.HeaderText = "Admin";
        //    chkUserType.Width = 50;


        //    DataGridViewButtonColumn btnUserHeader1 = new DataGridViewButtonColumn();
        //    btnUserHeader1.Name = "btnUserHeader1";
        //    btnUserHeader1.HeaderText = string.Empty;


        //    DataGridViewButtonColumn btnUserHeader2 = new DataGridViewButtonColumn();
        //    btnUserHeader2.Name = "btnUserHeader2";
        //    btnUserHeader2.HeaderText = string.Empty;

        //    dgUsers.Columns.Add(chkSelectUser);
        //    dgUsers.Columns.Add(UserId);
        //    dgUsers.Columns.Add(UserName);
        //    dgUsers.Columns.Add(Password);
        //    dgUsers.Columns.Add(chkUserType);
        //    dgUsers.Columns.Add(btnUserHeader1);
        //    dgUsers.Columns.Add(btnUserHeader2);

        //    bgWorker.DoWork -= bgWorker_DoWork_RefreshGridUser;
        //    bgWorker.RunWorkerCompleted -= bgWorker_Completed_RefreshGridUser;

        //    loadUserPage();
        //}

        private void bgWorker_DoWork_loadUserPage(object sender, DoWorkEventArgs e)
        {
            logger.Info("On bgWorker_DoWork_loadUserPage(object sender, DoWorkEventArgs e)");
            Int32 currentPageUser = 0;
            Object objCurrentPageUser = e.Argument as Object;
            if (objCurrentPageUser != null)
                currentPageUser = (Int32)objCurrentPageUser;

            InitializePagingUser(currentPageUser);
            string strSql = "";
            int intSkip = 0;
            if (this._mintUsercurrentPage > 0)
                intSkip = (this._mintUsercurrentPage * this._mintUserPageSize);

            // Select only the n records.
            strSql = "SELECT TOP " + this._mintUserPageSize +
                " * FROM " + tblUser.TableName + " WHERE " + tblUser.UserId + " NOT IN " +
                "(SELECT TOP " + intSkip + " " + tblUser.UserId + " FROM " + tblUser.TableName + ")";

            logger.Info("On bgWorker_DoWork_loadUserPage() With strSql:" + strSql);
            DataSet ds = new DataSet();
            ds = UserEntity.SelectSQLUser(strSql);
            if (ds != null)
            {
                _dtUser = ds.Tables[0];
                ds.Dispose();
            }

        }

        private void bgWorker_Completed_loadUserPage(object sender, RunWorkerCompletedEventArgs e)
        {
            logger.Info("On bgWorker_Completed_loadUserPage(object sender, RunWorkerCompletedEventArgs e)");
            // To show page status
            this.lblStatusUser.Text = (this._mintUsercurrentPage + 1).ToString() + " / " + this._mintUserPageCount.ToString();

            dgUsers.DataSource = _dtUser;
            cancelEditModeUser();
            _addModeUserFlag = false;
            _editModeUserFlag = false;
            bgWorker.DoWork -= bgWorker_DoWork_loadUserPage;
            bgWorker.RunWorkerCompleted -= bgWorker_Completed_loadUserPage;
        }

        #endregion BackgroundWorker User

        #endregion for Users

        #region for Customer

        /// <summary>
        /// To fill the Combobox with Customer name
        /// </summary>
        private void loadCustomerNameCombo()
        {
            logger.Info("On loadCustomerNameCombo()");
            comboBoxSort.DataSource = null;
            DataTable dtCustomerName = null;
            dtCustomerName = CustomerEntity.SelectAllCustomerNameWithId();

            comboBoxSort.DataSource = dtCustomerName;
            comboBoxSort.DisplayMember = "CustomerName";
            if (comboBoxSort.DataSource != null)
            {
                comboBoxSort.ValueMember = "CustomerId";
                comboBoxSort.SelectedIndex = -1;
            }
        }

        /// <summary>
        /// Set Default value for Customer Grid
        /// </summary>
        private void SetDefaultGridCustomer()
        {
            logger.Info("On SetDefaultGridCustomer()");
            _addModeCustomerFlag = false;
            _editModeCustomerFlag = false;
            RefreshGridCustomer(this._mintCustomercurrentPage);
        }

        /// <summary>
        /// It is used for refreshing Customer grid after the operation Insertion, Deletion and updation of the record. 
        /// </summary>
        /// <param name="currentPageCustomer"></param>
        /// <param name="searchKeyword">It is used for filtering according to selected word</param>
        private void RefreshGridCustomer(Int32 currentPageCustomer)
        {
            logger.Info("On RefreshGridCustomer(Int32 currentPageCustomer), currentPageCustomer:" + currentPageCustomer.ToString());
            try
            {
                dgCustomerName.DataSource = null;
                dgCustomerName.Columns.Clear();
                dgCustomerName.AllowUserToResizeColumns = false;
                dgCustomerName.AllowUserToResizeRows = false;

              //  ListSortDescription direction;
                //direction = ListSortDescription.Ascending;
                

                DataGridViewCheckBoxColumn chkSelectCustomer = new DataGridViewCheckBoxColumn();
                chkSelectCustomer.Name = "chkSelectCustomer";
                chkSelectCustomer.HeaderText = string.Empty;
                chkSelectCustomer.DisplayIndex = 0;
                chkSelectCustomer.Width = 40;

                DataGridViewTextBoxColumn CustomerId = new DataGridViewTextBoxColumn();
                CustomerId.DataPropertyName = "CustomerId";
                CustomerId.Name = "CustomerId";
                CustomerId.HeaderText = "CustomerId";
                CustomerId.Width = 100;
                CustomerId.Visible = false;

                DataGridViewTextBoxColumn CustomerName = new DataGridViewTextBoxColumn();
                CustomerName.DataPropertyName = "CustomerName";
                CustomerName.Name = "CustomerName";
                CustomerName.HeaderText = "Name";
                CustomerName.Width = 404;
              //  CustomerName.DisplayIndex = 1;

                DataGridViewButtonColumn btnCustomerHeader1 = new DataGridViewButtonColumn();
                btnCustomerHeader1.Name = "btnCustomerHeader1";
                btnCustomerHeader1.HeaderText = string.Empty;
                btnCustomerHeader1.Width = 58;


                DataGridViewButtonColumn btnCustomerHeader2 = new DataGridViewButtonColumn();
                btnCustomerHeader2.Name = "btnCustomerHeader2";
                btnCustomerHeader2.HeaderText = string.Empty;
                btnCustomerHeader2.Width = 58;

                dgCustomerName.Columns.Add(chkSelectCustomer);
                dgCustomerName.Columns.Add(CustomerId);
                dgCustomerName.Columns.Add(CustomerName);
                dgCustomerName.Columns.Add(btnCustomerHeader1);
                dgCustomerName.Columns.Add(btnCustomerHeader2);

               // dgCustomerName.Columns["CustomerName"].DisplayIndex = 0;

               // dgCustomerName.Sort(
                //dgCustomerName.Sort(dgCustomerName.Columns["CustomerName"], ListSortDirection.Ascending);

                //DataSet dataset = CustomerEntity.SelectCustomerBykeyword(searchKeyword);
                //if (dataset == null)
                //    return;
                //_dtCustomer = dataset.Tables[0];
                //dgCustomerName.DataSource = _dtCustomer;

                //cancelEditModeCustomer();
                //_addModeCustomerFlag = false;
                loadCustomerPage(currentPageCustomer);
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                dgCustomerName.EndEdit();
            }

        }
        /// <summary>
        /// For cancelling the edit mode of the grid 
        /// </summary>
        private void cancelEditModeCustomer()
        {
            logger.Info("On cancelEditModeCustomer()");
            foreach (DataGridViewRow row in dgCustomerName.Rows)
            {
                row.Cells["btnCustomerHeader1"].Value = "Edit";
                row.Cells["btnCustomerHeader2"].Value = "Delete";

                readOnlyTrueColumnsCustomer(row.Index);

                dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value = false;
            }
        }

        /// <summary>
        ///Only at the editing time of the row readonly will set to false
        /// </summary>
        /// <param name="rowIndex">Contains paticular row index </param>
        private void readOnlyTrueColumnsCustomer(int rowIndex)
        {
            logger.Info("On readOnlyTrueColumnsCustomer(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgCustomerName.Rows[rowIndex].Cells["CustomerName"].ReadOnly = true;
        }

        private void focusCustomerName(int rowIndex)
        {

            logger.Info("On focusCustomerName(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgCustomerName.Focus();
            dgCustomerName.CurrentCell = dgCustomerName.Rows[rowIndex].Cells["CustomerName"];
            dgCustomerName.CurrentCell.Style.BackColor = Color.LightGray;
            dgCustomerName.BeginEdit(true);

        }

        private void comboBoxSort_TextChanged(object sender, EventArgs e)
        {
            logger.Info("On comboBoxSort_TextChanged(object sender, EventArgs e)");
            RefreshGridCustomer(0);
        }

        /// <summary>
        ///Only at the editing time of the row readonly will set to false
        /// </summary>
        /// <param name="rowIndex">Contains paticular row index </param>
        private void readOnlyFalseColumnsCustomers(int rowIndex)
        {
            logger.Info("On readOnlyFalseColumnsCustomers(int rowIndex), rowIndex:" + rowIndex.ToString());
            dgCustomerName.Rows[rowIndex].Cells["CustomerName"].ReadOnly = false;

        }

        private void lnkCustomerAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkCustomerAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (_addModeCustomerFlag)
            {
                Dialogs.Exclamation("You already have one unsaved row on your tab.\nPlease either save or cancel it before adding another row.");
                return;
            }

            RefreshGridCustomer(this._mintCustomercurrentPage);

            _addModeCustomerFlag = true;
            DataRow dr = _dtCustomer.NewRow();
            dr[0] = 0;
            dr[1] = string.Empty;
            _dtCustomer.Rows.Add(dr);
            _dtCustomer.AcceptChanges();


            foreach (DataGridViewRow row in dgCustomerName.Rows)
                if (row.Index == dgCustomerName.RowCount - 1)
                {
                    readOnlyFalseColumnsCustomers(row.Index);

                    dgCustomerName.Rows[dgCustomerName.RowCount - 1].Cells["btnCustomerHeader1"].Value = "Add";
                    dgCustomerName.Rows[dgCustomerName.RowCount - 1].Cells["btnCustomerHeader2"].Value = "Cancel";

                    focusCustomerName(row.Index);
                }
                else
                {
                    readOnlyTrueColumnsCustomer(row.Index);
                    row.Cells["btnCustomerHeader1"].Value = "Edit";
                    row.Cells["btnCustomerHeader2"].Value = "Delete";
                }

        }

        private void lnkCustomerSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkCustomerSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            Boolean allChecked = true;

            foreach (DataGridViewRow row in dgCustomerName.Rows)
            {
                if (!(dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value.Equals(true)))
                {
                    allChecked = false;
                    dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value = true;
                }
            }
             
            if (allChecked)
                foreach (DataGridViewRow row in dgCustomerName.Rows)
               dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value = false;
        }

        //private void lnkCustomerSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    logger.Info("On lnkCustomerSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
        //    foreach (DataGridViewRow row in dgCustomerName.Rows)
        //    {
        //        dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value = true;
        //    }
        //}

        private void lnkCustomerDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkCustomerDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (dgCustomerName == null || dgCustomerName.RowCount == 0)
                return;

            if (_addModeCustomerFlag)
            {
                logger.Info("deletion cancelled, _addModeCustomerFlag:True");
                Dialogs.Exclamation("There are unsaved changes on the tab.\nPlease either save the row or cancel it from Cancel button");
                return;
            } 

            bool selectedRowCount = false;
            foreach (DataGridViewRow row in dgCustomerName.Rows)
                if (dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value != null && (bool)dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value)
                {
                    selectedRowCount = true;
                    break;
                }

            if (!selectedRowCount)
            {
                Dialogs.Exclamation("No record selected");
                return;
            }

            frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
            customBox.ShowDialog();
            if (customBox.DialogResult == System.Windows.Forms.DialogResult.No)
                return;

            Int32 selectedCount = 0;
            foreach (DataGridViewRow row in dgCustomerName.Rows)
            {
                if (dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value != null && (bool)dgCustomerName.Rows[row.Index].Cells["chkSelectCustomer"].Value)
                {
                    if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        Int32 customerId = Convert.ToInt32(dgCustomerName.Rows[row.Index].Cells["CustomerId"].Value);
                        logger.Info("Deleting customerId:" + customerId.ToString());
                        CustomerEntity.Delete(customerId);
                        logger.Info("Deleted customerId:" + customerId.ToString());
                        selectedCount++;
                    }

                }
            }

            //Maintan last page on delete
            Int32 currentPage = this._mintCustomercurrentPage;
            if (dgCustomerName.RowCount > selectedCount)
                currentPage = this._mintCustomercurrentPage;
            else if (currentPage > 0)
                currentPage--;
            else
                currentPage = 0;
            RefreshGridCustomer(currentPage);
            loadCustomerNameCombo();
        }

        private void dgCustomerName_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            logger.Info("On ");
            if (e.RowIndex >= 0)
            {

                if (e.ColumnIndex == dgCustomerName.Columns["btnCustomerHeader1"].Index)
                {
                    if (dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader1"].Value.ToString() == "Edit" && _addModeCustomerFlag == false && _editModeCustomerFlag == false)
                    {
                        logger.Info("On Edit Clicked");
                        readOnlyFalseColumnsCustomers(e.RowIndex);

                        dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader1"].Value = "Save";
                        dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader2"].Value = "Cancel";
                        _editModeCustomerFlag = true;
                        focusCustomerName(e.RowIndex);
                    }
                    else if (dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader1"].Value.ToString() == "Save")//Save
                    {
                        logger.Info("On Save Clicked, CustomerName:" + dgCustomerName.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString().Trim());
                        CustomerEntity customer = new CustomerEntity();
                        customer.CustomerId = Convert.ToInt32(dgCustomerName.Rows[e.RowIndex].Cells["CustomerId"].Value);
                        customer.CustomerName = dgCustomerName.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString().Trim();

                        if (string.IsNullOrEmpty(customer.CustomerName))
                        {
                            Dialogs.EmptyField();
                            return;
                        }

                        Boolean existCustomerFlag = false;
                        existCustomerFlag = CustomerEntity.IsExistCustomer(customer);
                        if (existCustomerFlag == false)
                        {
                            CustomerEntity.Update(customer);
                            cancelEditModeCustomer();
                            loadCustomerNameCombo();
                            _editModeCustomerFlag = false;
                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            focusCustomerName(e.RowIndex);
                        }                        
                    }

                    else if (dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader1"].Value.ToString() == "Add")//Add
                    {
                        logger.Info("On Add Clicked, CustomerName:" + dgCustomerName.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString().Trim());
                        CustomerEntity customer = new CustomerEntity();
                        customer.CustomerName = dgCustomerName.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString().Trim();

                        if (string.IsNullOrEmpty(customer.CustomerName))
                        {
                            Dialogs.EmptyField();
                            return;
                        }

                        Boolean existCustomerFlag = false;
                        existCustomerFlag = CustomerEntity.IsExistCustomer(customer);
                        if (existCustomerFlag == false)
                        {
                            CustomerEntity.Insert(customer);
                            RefreshGridCustomer(this._mintCustomercurrentPage);
                            loadCustomerNameCombo();
                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            focusCustomerName(e.RowIndex);
                        }                        
                    }
                }
                else if (e.ColumnIndex == dgCustomerName.Columns["btnCustomerHeader2"].Index)
                {
                    if (dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader2"].Value.ToString() == "Delete")
                    {
                        logger.Info("On Delete Clicked");
                        Int32 customerId = Convert.ToInt32(dgCustomerName.Rows[e.RowIndex].Cells["CustomerId"].Value);


                        frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
                        customBox.ShowDialog();

                        if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            logger.Info("Deleting customerId:" + customerId.ToString());
                            CustomerEntity.Delete(customerId);
                            logger.Info("Deleted customerId:" + customerId.ToString());
                            
                            //Maintan last page on delete
                            Int32 currentPage = this._mintCustomercurrentPage;
                            if (dgCustomerName.RowCount > 1)
                                currentPage = this._mintCustomercurrentPage;
                            else if (currentPage > 0)
                                currentPage--;
                            else
                                currentPage = 0;

                            RefreshGridCustomer(currentPage);
                            loadCustomerNameCombo();

                        }


                    }
                    else if (dgCustomerName.Rows[e.RowIndex].Cells["btnCustomerHeader2"].Value.ToString() == "Cancel") //Cancel
                    {
                        logger.Info("On Cancel Clicked");
                        _addModeCustomerFlag=false;
                        _editModeCustomerFlag = false;
                        RefreshGridCustomer(this._mintCustomercurrentPage);
                    }
                }


            }
        }

        private void dgCustomerName_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            logger.Info("On dgCustomerName_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)");
            if (String.IsNullOrEmpty(e.FormattedValue.ToString())) //run some custom validation on the value in that cell
            {
                dgCustomerName.Rows[e.RowIndex].ErrorText = "Customer Name must not be empty";
                //e.Cancel = true;
            }
            else
                dgCustomerName.Rows[e.RowIndex].ErrorText = String.Empty;

        }


        #region Pagination In Customer
        private int getCustomerCount()
        {
            int intCount = 0;
            string key = string.Empty;
            key = comboBoxSort.Text;
            intCount = CustomerEntity.SelectRowCountCustomerByFilter(key);
            logger.Info("On getCustomerCount() returns count:" + intCount.ToString());
            return intCount;
        }


        private void goCustomerFirst()
        {
            this._mintCustomercurrentPage = 0;
            loadCustomerPage(this._mintCustomercurrentPage);
        }

        private void goCustomerPrevious()
        {
            if (this._mintCustomercurrentPage == this._mintCustomerPageCount)
                this._mintCustomercurrentPage = this._mintCustomerPageCount - 1;

            this._mintCustomercurrentPage--;

            if (this._mintCustomercurrentPage < 1)
                this._mintCustomercurrentPage = 0;

            loadCustomerPage(this._mintCustomercurrentPage);
        }

        private void goCustomerNext()
        {
            this._mintCustomercurrentPage++;

            if (this._mintCustomercurrentPage > (this._mintCustomerPageCount - 1))
                this._mintCustomercurrentPage = this._mintCustomerPageCount - 1;

            loadCustomerPage(this._mintCustomercurrentPage);

        }

        private void goCustomerLast()
        {
            this._mintCustomercurrentPage = this._mintCustomerPageCount - 1;

            loadCustomerPage(this._mintCustomercurrentPage);
        }

        /// <summary>
        /// For Page view.Adjust page count if the last page contains partial page.
        /// </summary>
        /// <param name="currentPageMessage">It is the current page Index</param>
        private void InitializePagingCustomer(Int32 currentPageCustomer)
        {
            logger.Info("On InitializePagingCustomer(Int32 currentPageCustomer), currentPageCustomer:" + currentPageCustomer.ToString());
            this._mintCustomerPageSize = _pageCountCustomer;
            this._mintCustomerTotalRecords = getCustomerCount();
            this._mintCustomerPageCount = this._mintCustomerTotalRecords / this._mintCustomerPageSize;

            if (this._mintCustomerTotalRecords % this._mintCustomerPageSize > 0)
                this._mintCustomerPageCount++;

            this._mintCustomercurrentPage = currentPageCustomer;

        }
        /// <summary>
        /// For loading the selected page in pagination
        /// </summary>
        private void loadCustomerPage(Int32 currentPageCustomer)
        {
            logger.Info("On loadCustomerPage(Int32 currentPageCustomer), currentPageCustomer:" + currentPageCustomer.ToString());
            InitializePagingCustomer(currentPageCustomer);
            string strSql = "";
            int intSkip = 0;

            if (this._mintCustomercurrentPage > 0)
                intSkip = (this._mintCustomercurrentPage * this._mintCustomerPageSize);

            string searchKeyword = string.Empty;
            
            searchKeyword = comboBoxSort.Text;

            int SkipCustomers = (_mintCustomercurrentPage * 10);
           // Dialogs.Exclamation(Convert.ToString(_mintCustomerPageSize));


            strSql = "Select TOP 10 " + tblCustomer.CustomerId + ", " + tblCustomer.CustomerName + " from (Select ROW_NUMBER() Over (Order by " + tblCustomer.CustomerName + ") AS Row, " + tblCustomer.CustomerName + ", " + tblCustomer.CustomerId + " from " + tblCustomer.TableName + ") AS CUT WHERE Row > " + SkipCustomers + " AND " + tblCustomer.CustomerName + " Like '" + searchKeyword + "%'";            

       //     strSql = "SELECT TOP " + this._mintCustomerPageSize +
       //         " * FROM " + tblCustomer.TableName + " WHERE " + tblCustomer.CustomerName + " like '" + searchKeyword + "%' and " + tblCustomer.CustomerId + " NOT IN " +
      //          "(SELECT TOP " + intSkip + " " + tblCustomer.CustomerId + " FROM " + tblCustomer.TableName + " WHERE " + tblCustomer.CustomerName + " like '" + searchKeyword + "%')";


            logger.Info("On loadCustomerPage(), strSql:" + strSql);
            DataSet ds = new DataSet();
            ds = CustomerEntity.SelectSQLCustomer(strSql);

            DataTable Customers = new DataTable();

            if (ds == null)
                return;
            _dtCustomer = ds.Tables[0];
            dgCustomerName.DataSource = _dtCustomer;
            cancelEditModeCustomer();
            _addModeCustomerFlag = false;
            _editModeCustomerFlag = false;
            // To show page status
            this.lblStatusCustomer.Text = (this._mintCustomercurrentPage + 1).ToString() + " / " + this._mintCustomerPageCount.ToString();
            ds.Dispose();
        }

        private void btnCustomerFirst_Click(object sender, EventArgs e)
        {
            logger.Info("On btnCustomerFirst_Click(object sender, EventArgs e)");
            this.goCustomerFirst();
        }

        private void btnCustomerPrevious_Click(object sender, EventArgs e)
        {
            logger.Info("On btnCustomerPrevious_Click(object sender, EventArgs e)");
            this.goCustomerPrevious();
        }

        private void btnCustomerNext_Click(object sender, EventArgs e)
        {
            logger.Info("On btnCustomerNext_Click(object sender, EventArgs e)");
            this.goCustomerNext();
        }

        private void btnCustomerLast_Click(object sender, EventArgs e)
        {
            logger.Info("On btnCustomerLast_Click(object sender, EventArgs e)");
            this.goCustomerLast();
        }

        #endregion Pagination In Customer


        #endregion for Customer

        #region for Message

        /// <summary>
        /// Set Default value for Message Grid
        /// </summary>
        private void SetDefaultGridMessage()
        {
            logger.Info("On SetDefaultGridMessage()");
            _addModeMessageFlag = false;
            _editModeMessageFlag = false;
            RefreshGridMessage(this._mintMessagecurrentPage);
        }

        
        /// <summary>
        /// It is used for refreshing Message grid after the operation Insertion, Deletion and updation of the record. 
        /// </summary>
        /// <param name="currentPageMessage">currentPageMessage contains the Index of Currentpage</param>
        /// 
        private void RefreshGridMessage(Int32 currentPageMessage)
        {
            logger.Info("On RefreshGridMessage(Int32 currentPageMessage), currentPageMessage:" + currentPageMessage.ToString());
            try
            {
                DataTable myTable = new DataTable();
                myTable.Columns.AddRange(new DataColumn[] { new DataColumn("id") });
                myTable.Rows.Add(1);
                myTable.Rows.Add(2);

                dgMessage.DataSource = null;
                dgMessage.Columns.Clear();
                dgMessage.AllowUserToResizeColumns = false;
                dgMessage.AllowUserToResizeRows = false;

               // string apple = Convert.ToString(dgMessage.DefaultCellStyle.Font.Size);
               // Dialogs.Exclamation(apple);
                dgMessage.DefaultCellStyle.Font = new Font(dgMessage.DefaultCellStyle.Font.FontFamily, 7, FontStyle.Regular);

                DataGridViewCheckBoxColumn chkSelectMessage = new DataGridViewCheckBoxColumn();
                chkSelectMessage.Name = "chkSelectMessage";
                chkSelectMessage.HeaderText = string.Empty;
                chkSelectMessage.DisplayIndex = 0;
                chkSelectMessage.Width = 40;

                DataGridViewTextBoxColumn MessageId = new DataGridViewTextBoxColumn();
                MessageId.DataPropertyName = "MessageId";
                MessageId.Name = "MessageId";
                MessageId.HeaderText = "MessageId";
                MessageId.Width = 100;
                MessageId.Visible = false;

                DataGridViewTextBoxColumn MessageName = new DataGridViewTextBoxColumn();
                MessageName.DataPropertyName = "MessageName";
                MessageName.Name = "MessageName";
                MessageName.HeaderText = "Message";
                MessageName.MaxInputLength = 60;
                MessageName.Width = 250;


                DataGridViewComboBoxColumn AllowName = new DataGridViewComboBoxColumn();
                AllowName.DataPropertyName = "AllowName";
                AllowName.Name = "AllowName";
                AllowName.HeaderText = "Number of Names in the message";
                AllowName.DropDownWidth = 154;
                AllowName.Width = 154;
                AllowName.MaxDropDownItems = 5;
                AllowName.FlatStyle = FlatStyle.Flat;
                Int32 rowcount;
                for (rowcount = 0; rowcount < 3; rowcount++)
                {
                    AllowName.Items.Add(rowcount);
                }


                DataGridViewButtonColumn btnMessageHeader1 = new DataGridViewButtonColumn();
                btnMessageHeader1.Name = "btnMessageHeader1";
                btnMessageHeader1.HeaderText = string.Empty;
                btnMessageHeader1.Width = 58;

                DataGridViewButtonColumn btnMessageHeader2 = new DataGridViewButtonColumn();
                btnMessageHeader2.Name = "btnMessageHeader2";
                btnMessageHeader2.HeaderText = string.Empty;
                btnMessageHeader2.Width = 58;

                dgMessage.Columns.Add(chkSelectMessage);
                dgMessage.Columns.Add(MessageId);
                dgMessage.Columns.Add(MessageName);
                dgMessage.Columns.Add(AllowName);
                dgMessage.Columns.Add(btnMessageHeader1);
                dgMessage.Columns.Add(btnMessageHeader2);

                LoadMessagePage(currentPageMessage);

            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                dgMessage.EndEdit();
            }
        }
        /// <summary>
        /// For cancelling the edit mode of the grid 
        /// </summary>
        private void CancelEditModeMessage()
        {
            logger.Info("On CancelEditModeMessage()");
            foreach (DataGridViewRow row in dgMessage.Rows)
            {
                row.Cells["btnMessageHeader1"].Value = "Edit";
                row.Cells["btnMessageHeader2"].Value = "Delete";

                ReadOnlyTrueColumnsMessage(row.Index);

                dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value = false;
            }
        }


        private void FocusMessageName(int rowIndex)
        {
            logger.Info("On FocusMessageName(int rowIndex) , rowIndex:" + rowIndex.ToString());
            dgMessage.Focus();
            dgMessage.CurrentCell = dgMessage.Rows[rowIndex].Cells["AllowName"];
            dgMessage.CurrentCell.Style.BackColor = Color.LightGray;
            dgMessage.CurrentCell = dgMessage.Rows[rowIndex].Cells["MessageName"];
            dgMessage.CurrentCell.Style.BackColor = Color.LightGray;
            dgMessage.BeginEdit(true);

        }

        /// <summary>
        ///Only at the editing time of the row readonly will set to false
        /// </summary>
        /// <param name="rowIndex">Contains paticular row index </param>
        private void ReadOnlyFalseColumnsMessage(int rowIndex)
        {
            logger.Info("On ReadOnlyFalseColumnsMessage(int rowIndex) , rowIndex:" + rowIndex.ToString());
            dgMessage.Rows[rowIndex].Cells["MessageName"].ReadOnly = false;
            dgMessage.Rows[rowIndex].Cells["AllowName"].ReadOnly = false;
        }

        private void ReadOnlyTrueColumnsMessage(int rowIndex)
        {
            logger.Info("On ReadOnlyTrueColumnsMessage(int rowIndex) , rowIndex:" + rowIndex.ToString());
            dgMessage.Rows[rowIndex].Cells["MessageName"].ReadOnly = true;
            dgMessage.Rows[rowIndex].Cells["AllowName"].ReadOnly = true;
        }

        private String GetCaseInsensitiveMessageText(String messageText)
        {
            logger.Info("On GetCaseInsensitiveMessageText(String messageText), inputmessageText:" + messageText);
            if (messageText.ToUpper().Contains("NAME1") || messageText.ToUpper().Contains("NAME2"))
            {
                String messageString = Regex.Replace(messageText, "name1", "NAME1", RegexOptions.IgnoreCase);
                messageString = Regex.Replace(messageString, "name2", "NAME2", RegexOptions.IgnoreCase);
                messageText= messageString;
            }
            logger.Info("On GetCaseInsensitiveMessageText(String messageText), outputmessageText:" + messageText);
            return messageText;
        }

        private void dgMessage_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            logger.Info("On dgMessage_CellClick(object sender, DataGridViewCellEventArgs e)");
            if (e.RowIndex >= 0)
            {

                if (e.ColumnIndex == dgMessage.Columns["btnMessageHeader1"].Index)
                {
                    if (dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader1"].Value.ToString() == "Edit" && _addModeMessageFlag == false && _editModeMessageFlag == false)
                    {
                        logger.Info("On Edit Clicked");
                        ReadOnlyFalseColumnsMessage(e.RowIndex);
                        dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader1"].Value = "Save";
                        dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader2"].Value = "Cancel";
                        _editModeMessageFlag = true;
                        FocusMessageName(e.RowIndex);
                    }
                    else if (dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader1"].Value.ToString() == "Save")//Save
                    {
                        logger.Info("On Save Clicked, MessageName:" + dgMessage.Rows[e.RowIndex].Cells["MessageName"].Value.ToString().Trim());
                        MessageEntity message = new MessageEntity();
                        message.MessageId = Convert.ToInt32(dgMessage.Rows[e.RowIndex].Cells["MessageId"].Value);
                        message.MessageName = dgMessage.Rows[e.RowIndex].Cells["MessageName"].Value.ToString().Trim();
                       
                        message.AllowName = Convert.ToInt32(dgMessage.Rows[e.RowIndex].Cells["AllowName"].Value);
                        if (string.IsNullOrEmpty(message.MessageName))
                        {
                            Dialogs.EmptyField();
                            return;
                        }

                        message.MessageName = GetCaseInsensitiveMessageText(message.MessageName);
                        
                        Boolean existMessageFlag = false;
                        existMessageFlag = MessageEntity.IsExistMessage(message);
                        if (existMessageFlag == false)
                        {
                            dgMessage.Rows[e.RowIndex].Cells["AllowName"].Style.BackColor = Color.White;
                            dgMessage.Rows[e.RowIndex].Cells["MessageName"].Style.BackColor = Color.White;
                            MessageEntity.Update(message);
                            CancelEditModeMessage();
                            _editModeMessageFlag = false;
                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            FocusMessageName(e.RowIndex);
                        }


                    }

                    else if (dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader1"].Value.ToString() == "Add")//Add
                    {
                        logger.Info("On Add Clicked");
                        MessageEntity message = new MessageEntity();
                        message.MessageName = dgMessage.Rows[e.RowIndex].Cells["MessageName"].Value.ToString().Trim();
                        message.AllowName = Convert.ToInt32(dgMessage.Rows[e.RowIndex].Cells["AllowName"].Value);
                        if (string.IsNullOrEmpty(message.MessageName))
                        {
                            Dialogs.EmptyField();
                            return;
                        }

                        message.MessageName = GetCaseInsensitiveMessageText(message.MessageName);                        

                        Boolean existMessageFlag = false;
                        existMessageFlag = MessageEntity.IsExistMessage(message);
                        if (existMessageFlag == false)
                        {
                            MessageEntity.Insert(message);
                            RefreshGridMessage(this._mintMessagecurrentPage);

                        }
                        else
                        {
                            Dialogs.AlreadyExist();
                            FocusMessageName(e.RowIndex);
                        }

                    }
                }
                else if (e.ColumnIndex == dgMessage.Columns["btnMessageHeader2"].Index)
                {
                    if (dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader2"].Value.ToString() == "Delete")
                    {
                        logger.Info("On Delete Clicked");
                        Int32 messageId = Convert.ToInt32(dgMessage.Rows[e.RowIndex].Cells["MessageId"].Value);

                        frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
                        customBox.ShowDialog();

                        if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            logger.Info("Deleting messageId:" + messageId.ToString());
                            MessageEntity.Delete(messageId);
                            logger.Info("Deleted messageId:" + messageId.ToString());
                            
                            //Maintan last page on delete
                            Int32 currentPage = this._mintMessagecurrentPage;
                            if (dgMessage.RowCount > 1)
                                currentPage = this._mintMessagecurrentPage;
                            else if (currentPage > 0)
                                currentPage--;
                            else
                                currentPage = 0;
                            RefreshGridMessage(currentPage);

                        }


                    }
                    else if (dgMessage.Rows[e.RowIndex].Cells["btnMessageHeader2"].Value.ToString() == "Cancel") //Cancel
                    {
                        logger.Info("On Cancel Clicked");
                        _addModeMessageFlag = false;
                        _editModeMessageFlag = false;

                        RefreshGridMessage(this._mintMessagecurrentPage);
                    }
                }


            }
        }

        private void lnkMessageAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkMessageAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (_addModeMessageFlag)
            {
                Dialogs.Exclamation("You already have one unsaved row on your tab.\nPlease either save or cancel it before adding another row.");
                return;
            }

            RefreshGridMessage(this._mintMessagecurrentPage);

            _addModeMessageFlag = true;
            DataRow dr = _dtMessage.NewRow();
            dr[0] = 0;
            dr[1] = string.Empty;
            dr[2] = 0;
            _dtMessage.Rows.Add(dr);
            _dtMessage.AcceptChanges();

            foreach (DataGridViewRow row in dgMessage.Rows)
                if (row.Index == dgMessage.RowCount - 1)
                {
                    ReadOnlyFalseColumnsMessage(row.Index);

                    dgMessage.Rows[dgMessage.RowCount - 1].Cells["btnMessageHeader1"].Value = "Add";
                    dgMessage.Rows[dgMessage.RowCount - 1].Cells["btnMessageHeader2"].Value = "Cancel";

                    FocusMessageName(row.Index);
                }
                else
                {
                    ReadOnlyTrueColumnsMessage(row.Index);
                    row.Cells["btnMessageHeader1"].Value = "Edit";
                    row.Cells["btnMessageHeader2"].Value = "Delete";
                }

        }

        private void lnkMessageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkMessageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            Boolean allChecked = true;

            foreach (DataGridViewRow row in dgMessage.Rows)
            {
                if (!(dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value.Equals(true)))
                {
                    allChecked = false;
                    dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value = true;
                }
            }

            if (allChecked)
                foreach (DataGridViewRow row in dgMessage.Rows)
                    dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value = false;
        }

        //private void lnkMessageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    logger.Info("On lnkMessageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
        //    foreach (DataGridViewRow row in dgMessage.Rows)
        //    {
        //        dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value = true;
        //    }
        //}

        private void lnkMessageDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkMessageDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (dgMessage == null || dgMessage.RowCount == 0)
                return;

            if (_addModeMessageFlag)
            {
                logger.Info("On lnkMessageDelete_LinkClicked(), Delete Cancelled, _addModeMessageFlag:True");
                Dialogs.Exclamation("There are unsaved changes on the tab.\nPlease either save the row or cancel it from Cancel button");
                return;
            }

           bool selectedRowCount = false;
            foreach (DataGridViewRow row in dgMessage.Rows)
                if (dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value != null && (bool)dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value)
                {
                    selectedRowCount = true;
                    break;
                }

            if (!selectedRowCount)
            {
                Dialogs.Exclamation("No record selected");
                return;
            }

            frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
            customBox.ShowDialog();
            if (customBox.DialogResult == System.Windows.Forms.DialogResult.No)
                return;
            Int32 selectedCount = 0;
            foreach (DataGridViewRow row in dgMessage.Rows)
            {
                if (dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value != null && (bool)dgMessage.Rows[row.Index].Cells["chkSelectMessage"].Value)
                {
                    if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        Int32 messageId = Convert.ToInt32(dgMessage.Rows[row.Index].Cells["MessageId"].Value);
                        logger.Info("On lnkMessageDelete_LinkClicked(), Deleting messageId:" + messageId.ToString());
                        MessageEntity.Delete(messageId);
                        logger.Info("On lnkMessageDelete_LinkClicked(), Deleted messageId:" + messageId.ToString());
                        selectedCount++;
                    }
                }
            }
            //Maintan last page on delete
            Int32 currentPage = this._mintMessagecurrentPage;
            if (dgMessage.RowCount > selectedCount)
                currentPage = this._mintMessagecurrentPage;
            else if (currentPage > 0)
                currentPage--;
            else
                currentPage = 0;
            RefreshGridMessage(currentPage);
        }

        private void dgMessage_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            logger.Info("On dgMessage_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)");
            if (String.IsNullOrEmpty(e.FormattedValue.ToString())) //run some custom validation on the value in that cell
            {
                dgMessage.Rows[e.RowIndex].ErrorText = "Message Name must not be empty";
                //e.Cancel = true;
            }
            else
                dgMessage.Rows[e.RowIndex].ErrorText = String.Empty;

        }

        #region Pagination In Message

        /// <summary>
        /// Get total no of message in db 
        /// </summary>
        /// <returns>Count of Message</returns>
        private int GetMessageCount()
        {
            int intCount = 0;
            intCount = MessageEntity.SelectRowCountMessage();
            logger.Info("On GetMessageCount(), Count:" + intCount.ToString());
            return intCount;
        }

        /// <summary>
        /// Go to the first Message page
        /// </summary>
        private void GoMessageFirst()
        {
            this._mintMessagecurrentPage = 0;

            LoadMessagePage(this._mintMessagecurrentPage);
        }

        /// <summary>
        /// Go to the prev. Message page
        /// </summary>
        private void GoMessagePrevious()
        {
            if (this._mintMessagecurrentPage == this._mintMessagePageCount)
                this._mintMessagecurrentPage = this._mintMessagePageCount - 1;

            this._mintMessagecurrentPage--;

            if (this._mintMessagecurrentPage < 1)
                this._mintMessagecurrentPage = 0;

            LoadMessagePage(this._mintMessagecurrentPage);
        }

        /// <summary>
        /// Go to the next Message page
        /// </summary>
        private void GoMessageNext()
        {
            this._mintMessagecurrentPage++;

            if (this._mintMessagecurrentPage > (this._mintMessagePageCount - 1))
                this._mintMessagecurrentPage = this._mintMessagePageCount - 1;

            LoadMessagePage(this._mintMessagecurrentPage);
        }

        /// <summary>
        /// Go to the last Message page
        /// </summary>
        private void GoMessageLast()
        {
            this._mintMessagecurrentPage = this._mintMessagePageCount - 1;

            LoadMessagePage(this._mintMessagecurrentPage);
        }

        /// <summary>
        /// For Page view.Adjust page count if the last page contains partial page.
        /// </summary>
        /// <param name="currentPageMessage">It is the current page Index</param>
        private void InitializePagingMessage(Int32 currentPageMessage)
        {
            logger.Info("On InitializePagingMessage(Int32 currentPageMessage), currentPageMessage:" + currentPageMessage.ToString());
            this._mintMessagePageSize = _pageCountMessage;
            this._mintMessageTotalRecords = GetMessageCount();
            this._mintMessagePageCount = this._mintMessageTotalRecords / this._mintMessagePageSize;

            if (this._mintMessageTotalRecords % this._mintMessagePageSize > 0)
                this._mintMessagePageCount++;

            this._mintMessagecurrentPage = currentPageMessage;

        }

        /// <summary>
        /// For loading the selected page in pagination
        /// </summary>
        private void LoadMessagePage(Int32 currentPageMessage)
        {
            logger.Info("On LoadMessagePage(Int32 currentPageMessage), currentPageMessage:" + currentPageMessage.ToString());
            InitializePagingMessage(currentPageMessage);
            string strSql = "";
            int intSkip = 0;
            if (this._mintMessagecurrentPage > 0)
                intSkip = (this._mintMessagecurrentPage * this._mintMessagePageSize);

            // Select only the n records.
            strSql = "SELECT TOP " + this._mintMessagePageSize +
                " * FROM " + tblMessage.TableName + " WHERE " + tblMessage.MessageId + " NOT IN " +
                "(SELECT TOP " + intSkip + " " + tblMessage.MessageId + " FROM " + tblMessage.TableName + ")";

            logger.Info("On LoadMessagePage(), strSql:" + strSql);
            DataSet ds = new DataSet();
            ds = MessageEntity.SelectSQLMessage(strSql);
            if (ds == null)
                return;
            _dtMessage = ds.Tables[0];
            dgMessage.DataSource = _dtMessage;
            CancelEditModeMessage();
            _addModeMessageFlag = false;
            _editModeMessageFlag = false;

            // To show page status
            this.lblStatusMessage.Text = (this._mintMessagecurrentPage + 1).ToString() + " / " + this._mintMessagePageCount.ToString();
            ds.Dispose();
        }

        private void btnMessageFirst_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMessageFirst_Click(object sender, EventArgs e)");
            this.GoMessageFirst();
        }

        private void btnMessagePrevious_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMessagePrevious_Click(object sender, EventArgs e)");
            this.GoMessagePrevious();
        }

        private void btnMessageNext_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMessageNext_Click(object sender, EventArgs e)");
            this.GoMessageNext();
        }

        private void btnMessageLast_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMessageLast_Click(object sender, EventArgs e)");
            this.GoMessageLast();
        }

        #endregion Pagination In Message

        #endregion for Message

        #region For Image

        /// <summary>
        /// It is used for refreshing Image grid after the operation Insertion, Deletion and updation of the record. 
        /// </summary>
        /// <param name="currentPageImage">currentPageImage contains the Index of Currentpage</param>
        /// 
        private void RefreshGridImage(Int32 currentPageImage)
        {
            logger.Info("On RefreshGridImage(Int32 currentPageImage), currentPageImage:" + currentPageImage.ToString());
            try
            {
                dgImage.DataSource = null;
                dgImage.Columns.Clear();
                dgImage.AllowUserToResizeColumns = false;
                dgImage.AllowUserToResizeRows = false;

                DataGridViewCheckBoxColumn chkSelectImage = new DataGridViewCheckBoxColumn();
                chkSelectImage.Name = "chkSelectImage";
                chkSelectImage.HeaderText = string.Empty;
                chkSelectImage.DisplayIndex = 0;
                chkSelectImage.Width = 40;

                DataGridViewTextBoxColumn ImageId = new DataGridViewTextBoxColumn();
                ImageId.DataPropertyName = "ImageId";
                ImageId.Name = "ImageId";
                ImageId.HeaderText = "ImageId";
                ImageId.Width = 100;
                ImageId.Visible = false;

                DataGridViewImageColumn ImageData = new DataGridViewImageColumn();
                ImageData.DataPropertyName = "ImageData";
                ImageData.Name = "ImageData";
                ImageData.HeaderText = "Photo";
                ImageData.Width = 404;
                ImageData.ImageLayout = DataGridViewImageCellLayout.Stretch;

                DataGridViewButtonColumn btnImageHeader2 = new DataGridViewButtonColumn();
                btnImageHeader2.Name = "btnImageHeader2";
                btnImageHeader2.HeaderText = string.Empty;
                btnImageHeader2.Width = 116;


                dgImage.Columns.Add(chkSelectImage);
                dgImage.Columns.Add(ImageId);
                dgImage.Columns.Add(ImageData);
                dgImage.Columns.Add(btnImageHeader2);


                LoadArchivePage(currentPageImage);
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                dgImage.EndEdit();
            }

        }

        private void CancelEditModeImage()
        {
            logger.Info("On CancelEditModeImage()");
            foreach (DataGridViewRow row in dgImage.Rows)
            {
                row.Cells["btnImageHeader2"].Value = "Delete";
                dgImage.Rows[row.Index].Cells["chkSelectImage"].Value = false;
                //dgImage.Rows[row.Index].Height = 100;
            }
        }

        private void dgImage_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            logger.Info("On dgImage_CellContentClick(object sender, DataGridViewCellEventArgs e)");
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgImage.Columns["btnImageHeader2"].Index)
                {
                    if (dgImage.Rows[e.RowIndex].Cells["btnImageHeader2"].Value.ToString() == "Delete")
                    {
                        Int32 imageId = Convert.ToInt32(dgImage.Rows[e.RowIndex].Cells["ImageId"].Value);

                        frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
                        customBox.ShowDialog();

                        if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            logger.Info("Deleting ImageId:" + imageId.ToString());
                            ImageEntity.Delete(imageId);
                            logger.Info("Deleted ImageId:" + imageId.ToString());
                           
                            //Maintan last page on delete
                            Int32 currentPage = this._mintArchivecurrentPage;
                            if (dgImage.RowCount > 1)
                                currentPage = this._mintArchivecurrentPage;
                            else if (currentPage > 0)
                                currentPage--;
                            else
                                currentPage = 0;
                            RefreshGridImage(currentPage);
                        }

                    }
                    else if (dgImage.Rows[e.RowIndex].Cells["btnImageHeader2"].Value.ToString() == "Cancel") //Cancel
                    {
                        logger.Info("Clicked on Cancel");
                        RefreshGridImage(this._mintArchivecurrentPage);
                    }
                }
            }
        }

        private void lnkImageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkImageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            Boolean allChecked = true;

            foreach (DataGridViewRow row in dgImage.Rows)
            {
                if (!(dgImage.Rows[row.Index].Cells["chkSelectImage"].Value.Equals(true)))
                {
                    allChecked = false;
                    dgImage.Rows[row.Index].Cells["chkSelectImage"].Value = true;
                }
            }

            if (allChecked)
                foreach (DataGridViewRow row in dgImage.Rows)
                    dgImage.Rows[row.Index].Cells["chkSelectImage"].Value = false;
        }

        //private void lnkImageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    logger.Info("On lnkImageSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
        //    foreach (DataGridViewRow row in dgImage.Rows)
        //    {
        //        dgImage.Rows[row.Index].Cells["chkSelectImage"].Value = true;
        //    }
        //}

        private void lnkImageDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logger.Info("On lnkImageDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)");
            if (dgImage == null || dgImage.RowCount == 0)
                return;

            bool selectedRowCount = false;
            foreach (DataGridViewRow row in dgImage.Rows)
                if (dgImage.Rows[row.Index].Cells["chkSelectImage"].Value != null && (bool)dgImage.Rows[row.Index].Cells["chkSelectImage"].Value)
                {
                    selectedRowCount = true;
                    break;
                }

            if (!selectedRowCount)
            {
                Dialogs.Exclamation("No record selected");
                return;
            }

            frmDialog customBox = new frmDialog("Delete Selected Records", "Delete Selected Records");
            customBox.ShowDialog();
            if (customBox.DialogResult == System.Windows.Forms.DialogResult.No)
                return;

            Int32 selectedCount = 0;
            foreach (DataGridViewRow row in dgImage.Rows)
            {
                if (dgImage.Rows[row.Index].Cells["chkSelectImage"].Value != null && (bool)dgImage.Rows[row.Index].Cells["chkSelectImage"].Value)
                    if (customBox.DialogResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        Int32 imageId = Convert.ToInt32(dgImage.Rows[row.Index].Cells["ImageId"].Value);
                        logger.Info("On lnkImageDelete_LinkClicked(), deleting imageId:" + imageId.ToString());
                        ImageEntity.Delete(imageId);
                        logger.Info("On lnkImageDelete_LinkClicked(), deleted imageId:" + imageId.ToString());
                        selectedCount++;
                    }
            }

            //Maintan last page on delete
            Int32 currentPage = this._mintArchivecurrentPage;
            if (dgImage.RowCount > selectedCount)
                currentPage = this._mintArchivecurrentPage;
            else if (currentPage > 0)
                currentPage--;
            else
                currentPage = 0;
            RefreshGridImage(currentPage);
        }

        #region  Pagination In Image

        /// <summary>
        /// Get total no of archive record count from db
        /// </summary>
        /// <returns>Total Row count</returns>
        private int GetArchiveCount()
        {
            logger.Info("On GetArchiveCount()");
            int intCount = 0;
            intCount = ImageEntity.SelectRowCountImage();
            logger.Info("On GetArchiveCount(), Count:" + intCount.ToString());
            return intCount;
        }

        /// <summary>
        /// Go to first archive page
        /// </summary>
        private void GoArchiveFirst()
        {
            this._mintArchivecurrentPage = 0;

            LoadArchivePage(this._mintArchivecurrentPage);
        }

        /// <summary>
        /// Go to prev. archive page
        /// </summary>
        private void GoArchivePrevious()
        {
            if (this._mintArchivecurrentPage == this._mintArchivePageCount)
                this._mintArchivecurrentPage = this._mintArchivePageCount - 1;

            this._mintArchivecurrentPage--;

            if (this._mintArchivecurrentPage < 1)
                this._mintArchivecurrentPage = 0;

            LoadArchivePage(this._mintArchivecurrentPage);
        }

        /// <summary>
        /// Go to next archive page
        /// </summary>
        private void GoArchiveNext()
        {
            this._mintArchivecurrentPage++;

            if (this._mintArchivecurrentPage > (this._mintArchivePageCount - 1))
                this._mintArchivecurrentPage = this._mintArchivePageCount - 1;

            LoadArchivePage(this._mintArchivecurrentPage);
        }

        /// <summary>
        /// Go to last archive page
        /// </summary>
        private void GoArchiveLast()
        {
            this._mintArchivecurrentPage = this._mintArchivePageCount - 1;

            LoadArchivePage(this._mintArchivecurrentPage);
        }
        /// <summary>
        /// For Page view.Adjust page count if the last page contains partial page.
        /// </summary>
        /// <param name="currentPageMessage">It is the current page Index</param>
        private void InitializePagingImage(Int32 currentPageImage)
        {
            logger.Info("On InitializePagingImage(Int32 currentPageImage) , currentPageImage:" + currentPageImage.ToString());
            // For Page view.
            this._mintArchivePageSize = _pageCountArchive;
            this._mintArchiveTotalRecords = GetArchiveCount();
            this._mintArchivePageCount = this._mintArchiveTotalRecords / this._mintArchivePageSize;

            // Adjust page count if the last page contains partial page.
            if (this._mintArchiveTotalRecords % this._mintArchivePageSize > 0)
                this._mintArchivePageCount++;

            this._mintArchivecurrentPage = currentPageImage;

        }

        /// <summary>
        /// To load archive page
        /// </summary>
        /// <param name="currentPageImage">page no. to be load</param>
        private void LoadArchivePage(Int32 currentPageImage)
        {
            logger.Info("On LoadArchivePage(Int32 currentPageImage) , currentPageImage:" + currentPageImage.ToString());
            InitializePagingImage(currentPageImage);

            string strSql = "";
            int intSkip = 0;

            if (this._mintArchivecurrentPage > 0)
                intSkip = (this._mintArchivecurrentPage * this._mintArchivePageSize);

            strSql = "SELECT TOP " + this._mintArchivePageSize + " " + tblImage.TableName + "." + tblImage.ImageId + "," + tblImage.ImageData +
            " FROM " + tblImage.TableName + " INNER JOIN " + tblArchive.TableName + " ON " + tblImage.TableName + "." + tblImage.ImageId + " = " + tblArchive.TableName + "." + tblArchive.ImageId + " WHERE " + tblImage.TableName + "." + tblImage.ImageId + " NOT IN " +
            "(SELECT TOP " + intSkip + " " + tblImage.TableName + "." + tblImage.ImageId + " FROM " + tblImage.TableName + " INNER JOIN " + tblArchive.TableName + " ON " + tblImage.TableName + "." + tblImage.ImageId + " = " + tblArchive.TableName + "." + tblArchive.ImageId + ")";
            logger.Info("On LoadArchivePage(), strSql:" + strSql);
            DataSet ds = new DataSet();
            ds = ImageEntity.SelectSQLImage(strSql);
            if (ds == null)
                return;
            _dtArchive = ds.Tables[0];
            dgImage.DataSource = _dtArchive;
            CancelEditModeImage();

            // To show page status
            this.lblStatusImage.Text = (this._mintArchivecurrentPage + 1).ToString() + " / " + this._mintArchivePageCount.ToString();
            ds.Dispose();
        }

        private void btnImageFirst_Click(object sender, EventArgs e)
        {
            logger.Info("On btnImageFirst_Click(object sender, EventArgs e)");
            this.GoArchiveFirst();
        }

        private void btnImagePrevious_Click(object sender, EventArgs e)
        {
            logger.Info("On btnImagePrevious_Click(object sender, EventArgs e)");
            this.GoArchivePrevious();
        }

        private void btnImageNext_Click(object sender, EventArgs e)
        {
            logger.Info("On btnImageNext_Click(object sender, EventArgs e)");
            this.GoArchiveNext();
        }

        private void btnImageLast_Click(object sender, EventArgs e)
        {
            logger.Info("On btnImageLast_Click(object sender, EventArgs e)");
            this.GoArchiveLast();
        }


        #endregion   Pagination In Image

        #endregion for Image

        private void ClearSelection()
        {
            logger.Info("On ClearSelection() i.e. set everything to default");
            this.btnUser.Image = global::MarqueeMoment.Properties.Resources.user_bttn_54_209;
            this.btnArchive.Image = global::MarqueeMoment.Properties.Resources.manage_archive_bttn_52_264;
            this.btnCustomer.Image = global::MarqueeMoment.Properties.Resources.customer_names_bttn_52_319;
            this.btnMessage.Image = global::MarqueeMoment.Properties.Resources.messages_bttn_52_374;
            
            pnlArchive.Visible = false;
            pnlUser.Visible = false;
            pnlMessage.Visible = false;
            pnlCustomer.Visible = false;
        }

        private bool ValidateGridValues()
        {
            logger.Info("On ValidateGridValues()with Values- \n_addModeUserFlag:" + _addModeUserFlag.ToString() + "\n_editModeUserFlag:" + _editModeUserFlag.ToString() + "\n_addModeCustomerFlag:" + _addModeCustomerFlag.ToString() + "\n_editModeCustomerFlag:" + _editModeCustomerFlag.ToString() + "\n_addModeMessageFlag:" + _addModeMessageFlag.ToString() + "\n_editModeMessageFlag:" + _editModeMessageFlag.ToString());
            if (_addModeUserFlag || _editModeUserFlag || _addModeCustomerFlag || _editModeCustomerFlag || _addModeMessageFlag || _editModeMessageFlag)
            {
                switch (selectedAdmin)
                {
                    case 1:
                        if (dgUsers != null && dgUsers.RowCount > 0 && (_addModeUserFlag || _editModeUserFlag))
                        {
                            logger.Info("On ValidateGridValues() Warning:There are unsaved changes on the tab, do you still want to continue?");
                            frmDialog customBox = new frmDialog("Warning", "There are unsaved changes on the tab, do you still want to continue?");
                            if (customBox.ShowDialog() == System.Windows.Forms.DialogResult.No)
                            {
                                return false;
                            }
                            else
                            {
                                SetDefaultGridUser();
                            }

                        }
                        break;
                    case 2:
                        break;
                    case 3:
                        if (dgCustomerName != null && dgCustomerName.RowCount > 0 && (_addModeCustomerFlag || _editModeCustomerFlag))
                        {
                            logger.Info("On ValidateGridValues() Warning:There are unsaved changes on the tab, do you still want to continue?");
                            frmDialog customBox = new frmDialog("Warning", "There are unsaved changes on the tab, do you still want to continue?");
                            if (customBox.ShowDialog() == System.Windows.Forms.DialogResult.No)
                            {
                                return false;
                            }
                            else
                            {
                                SetDefaultGridCustomer();
                            }

                        }
                        break;
                    case 4:
                        if (dgMessage != null && dgMessage.RowCount > 0 && (_addModeMessageFlag || _editModeMessageFlag))
                        {
                            logger.Info("On ValidateGridValues() Warning:There are unsaved changes on the tab, do you still want to continue?");
                            frmDialog customBox = new frmDialog("Warning", "There are unsaved changes on the tab, do you still want to continue?");
                            if (customBox.ShowDialog() == System.Windows.Forms.DialogResult.No)
                            {
                                return false;
                            }
                            else
                            {
                                SetDefaultGridMessage();
                            }

                        }

                        break;
                    default:
                        break;
                }


            }
            return true;
        }

        /// <summary>
        /// To Show Time on Time Box
        /// </summary>
        private void ShowTime()
        {
            String currentTime = String.Empty;
            var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            currentTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToLongTimeString();
            lblPM.Text = currentTime.Substring(currentTime.Length - 2);
            currentTime = currentTime.Substring(0, currentTime.Length - 3);

            lblT8.Text = currentTime.Substring(currentTime.Length - 1);
            lblT7.Text = currentTime.Substring(currentTime.Length - 2, 1);
            lblT6.Text = currentTime.Substring(currentTime.Length - 3, 1);
            lblT5.Text = currentTime.Substring(currentTime.Length - 4, 1);
            lblT4.Text = currentTime.Substring(currentTime.Length - 5, 1);
            lblT3.Text = currentTime.Substring(currentTime.Length - 6, 1);
            lblT2.Text = currentTime.Substring(currentTime.Length - 7, 1);

            if (currentTime.Length == 7)
                lblT1.Text = String.Empty;
            else
                lblT1.Text = currentTime.Substring(currentTime.Length - 8, 1);
        }

        #endregion User defined Methods

        #region System Events

        private void btnMainMenu_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMainMenu_Click(object sender, EventArgs e)");
            this.Close();
        }

        private void btnUser_Click(object sender, EventArgs e)
        {
            logger.Info("On btnUser_Click(object sender, EventArgs e)");
            if (selectedAdmin == 1)
                return;

            if (!ValidateGridValues())
                return;

            ClearSelection();
            pnlUser.Visible = true;
            this.btnUser.Image = global::MarqueeMoment.Properties.Resources.user_hover_bttn_54_209;
            selectedAdmin = 1;

            if (!_loadUserFlag)
            {
                RefreshGridUser(0);
                _loadUserFlag = true;
            }
        }

        private void btnArchive_Click(object sender, EventArgs e)
        {
            logger.Info("On btnArchive_Click(object sender, EventArgs e)");
            if (selectedAdmin == 2)
                return;

            if (!ValidateGridValues())
                return;

            ClearSelection();
            pnlArchive.Visible = true;
            this.btnArchive.Image = global::MarqueeMoment.Properties.Resources.manage_archive_hover_52_264;
            selectedAdmin = 2;

            if (!_loadArchiveFlag)
            {
                //Delete old archive records from db
                var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
                DateTime currentDate = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone);
                ArchiveEntity.DeleteOldArchive(currentDate.AddDays(-7));
                RefreshGridImage(0);
                _loadArchiveFlag = true;
            }
        }

        private void btnCustomer_Click(object sender, EventArgs e)
        {
            logger.Info("On btnCustomer_Click(object sender, EventArgs e)");
            if (selectedAdmin == 3)
                return;

            if (!ValidateGridValues())
                return;

            ClearSelection();
            pnlCustomer.Visible = true;
            this.btnCustomer.Image = global::MarqueeMoment.Properties.Resources.customer_names_hover_52_319;
            selectedAdmin = 3;

            if (!_loadCustomerFlag)
            {
                RefreshGridCustomer(0);
                _loadCustomerFlag = true;
            }
            comboBoxSort.Text = string.Empty;
            comboBoxSort.Focus();
        }

        private void btnMessage_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMessage_Click(object sender, EventArgs e)");
            if (selectedAdmin == 4)
                return;

            if (!ValidateGridValues())
                return;

            ClearSelection();
            pnlMessage.Visible = true;
            this.btnMessage.Image = global::MarqueeMoment.Properties.Resources.messages_hover_52_374;
            selectedAdmin = 4;

            if (!_loadMessageFlag)
            {
                RefreshGridMessage(0);
                _loadMessageFlag = true;
            }
        }

        private void timerAdmin_Tick(object sender, EventArgs e)
        {
            ShowTime();
        }

        #endregion System Events


    }
}
